<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\SessionHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionsController extends Controller
{
    use SessionHelper;

    public function __construct()
    {
        $this->middleware('guest',['only'=>['create']]);
    }

    public function create()
    {
        return view('sessions.create');
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|max:255',
            'password' => 'required'
        ]);
        $name = $this->username($request->name);
        if (Auth::attempt([$name=>$request->name,'password'=>$request->password],$request->has('remember'))){
            if(Auth::user()->activated) {
                session()->flash('success', '欢迎回来！');
                $fallback = route('users.show', Auth::user());
                return redirect()->intended($fallback);
            } else {
                Auth::logout();
                session()->flash('warning', '你的账号未激活，请检查邮箱中的注册邮件进行激活。');
                return redirect('/');
            }
        }else{
            session()->flash('danger','账号或者密码错误');
            return redirect()->back()->withInput();
        }
    }

    public function destroy()
    {
        Auth::logout();
        session()->flash('success','退出登录');
        return redirect()->route('home');
    }
}
